package com.training.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.Settings;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;

import com.base.BaseActivity;
import com.base.PermissionCallback;
import com.base.PermissionHelper;
import com.training.bean.User;
import com.training.databinding.ActivityStartBinding;

import java.util.Map;

public class StartActivity extends BaseActivity<ActivityStartBinding> {
    private ActivityResultLauncher<String[]> multiplePermissionLauncher;
    private PermissionHelper permissionHelper;
    private PermissionCallback permissionCallback;
    @Override
    public ActivityStartBinding binding() {
        return ActivityStartBinding.inflate(getLayoutInflater());
    }

    @Override
    public void onCreated(Bundle savedInstanceState) {
        // 初始化权限助手
        permissionHelper = new PermissionHelper(this);

        // 初始化权限回调
        permissionCallback = new PermissionCallback() {
            @Override
            public void onAllPermissionsGranted() {
                toApp();
            }

            @Override
            public void onPermissionsDenied() {
                showPermissionDeniedDialog();
            }
        };

        // 初始化权限请求Launcher
        initPermissionLauncher();

        // 检查并请求权限
        checkAndRequestPermissions();
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (permissionHelper.checkAllPermissions()) {
            toApp();
        }
    }

    @Override
    public void loadData() {

    }

    @Override
    public void refreshUI() {

    }
    private void checkAndRequestPermissions() {
        if (permissionHelper.checkAllPermissions()) {
            toApp();
        } else {
            permissionHelper.requestPermissions(multiplePermissionLauncher);
        }
    }
    private void initPermissionLauncher() {
        multiplePermissionLauncher = registerForActivityResult(
                new ActivityResultContracts.RequestMultiplePermissions(),
                result -> {
                    boolean allGranted = true;
                    for (Map.Entry<String, Boolean> entry : result.entrySet()) {
                        if (!entry.getValue()) {
                            allGranted = false;
                            break;
                        }
                    }

                    if (allGranted) {
                        permissionCallback.onAllPermissionsGranted();
                    } else {
                        permissionCallback.onPermissionsDenied();
                    }
                }
        );
    }

    private void toApp() {
        User user = dc.getUser();
        if (user != null) {
            // 权限已获得，延迟跳转到主界面
            new Handler().postDelayed(() -> {
                startActivity(new Intent(this, HomeActivity.class));
                finish();
            }, 1000); // 延迟1秒跳转
        } else {
            // 权限已获得，延迟跳转到主界面
            new Handler().postDelayed(() -> {
                startActivity(new Intent(this, LoginActivity.class));
                finish();
            }, 1000); // 延迟1秒跳转
        }
    }

    private void showPermissionDeniedDialog() {
        new AlertDialog.Builder(this)
                .setTitle("权限申请")
                .setMessage("应用需要必要的权限才能正常运行，请在设置中授予所有权限。")
                .setPositiveButton("去设置", (dialog, which) -> {
                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    Uri uri = Uri.fromParts("package", getPackageName(), null);
                    intent.setData(uri);
                    startActivity(intent);
                })
                .setNegativeButton("退出", (dialog, which) -> finish())
                .setCancelable(false)
                .show();
    }
}
